import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { 
  Button, 
  List, 
  Modal, 
  Form, 
  Input, 
  Switch, 
  Popconfirm,
  Empty 
} from 'antd';
import { 
  ArrowLeftOutlined, 
  PlusOutlined, 
  EditOutlined, 
  DeleteOutlined, 
  EnvironmentOutlined 
} from '@ant-design/icons';
import { 
  getAddresses, 
  addAddress, 
  updateAddress, 
  deleteAddress 
} from '../../utils/storage';
import { message } from '../../utils/message';
import './AddressManagement.css';

const AddressManagement = () => {
  const navigate = useNavigate();
  const [addresses, setAddresses] = useState([]);
  const [modalVisible, setModalVisible] = useState(false);
  const [editingAddress, setEditingAddress] = useState(null);
  const [form] = Form.useForm();

  useEffect(() => {
    loadAddresses();
  }, []);

  const loadAddresses = () => {
    const userAddresses = getAddresses();
    setAddresses(userAddresses);
  };

  const handleAdd = () => {
    setEditingAddress(null);
    form.resetFields();
    setModalVisible(true);
  };

  const handleEdit = (address) => {
    setEditingAddress(address);
    form.setFieldsValue(address);
    setModalVisible(true);
  };

  const handleDelete = (addressId) => {
    deleteAddress(addressId);
    loadAddresses();
    message.success('地址已删除');
  };

  const handleSetDefault = (addressId) => {
    const updatedAddresses = addresses.map(addr => ({
      ...addr,
      isDefault: addr.id === addressId
    }));
    
    // 更新每个地址的默认状态
    updatedAddresses.forEach(addr => {
      updateAddress(addr.id, { isDefault: addr.isDefault });
    });
    
    loadAddresses();
    message.success('默认地址已设置');
  };

  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      
      if (editingAddress) {
        // 编辑地址
        updateAddress(editingAddress.id, values);
        message.success('地址已更新');
      } else {
        // 新增地址
        const isFirstAddress = addresses.length === 0;
        addAddress({
          ...values,
          isDefault: isFirstAddress // 第一个地址自动设为默认
        });
        message.success('地址已添加');
      }
      
      setModalVisible(false);
      loadAddresses();
    } catch (error) {
      message.error('操作失败');
    }
  };

  return (
    <div className="address-management">
      {/* 头部导航 */}
      <div className="address-header">
        <Button 
          type="text" 
          icon={<ArrowLeftOutlined />}
          onClick={() => navigate(-1)}
        />
        <span className="header-title">地址管理</span>
        <Button 
          type="text" 
          icon={<PlusOutlined />}
          onClick={handleAdd}
        />
      </div>

      {/* 地址列表 */}
      {addresses.length === 0 ? (
        <div style={{ padding: '40px 16px', textAlign: 'center' }}>
          <Empty 
            description="还没有收货地址"
            image={Empty.PRESENTED_IMAGE_SIMPLE}
          />
          <Button 
            type="primary" 
            icon={<PlusOutlined />}
            onClick={handleAdd}
            style={{ marginTop: '16px' }}
          >
            添加收货地址
          </Button>
        </div>
      ) : (
        <div className="address-list">
          {addresses.map(address => (
            <div key={address.id} className="address-item">
              <div className="address-main">
                <div className="address-header-info">
                  <div className="receiver-info">
                    <span className="receiver-name">{address.name}</span>
                    <span className="receiver-phone">{address.phone}</span>
                    {address.isDefault && (
                      <span className="default-tag">默认</span>
                    )}
                  </div>
                  <div className="address-actions">
                    <Button 
                      type="text" 
                      size="small"
                      icon={<EditOutlined />}
                      onClick={() => handleEdit(address)}
                    />
                    <Popconfirm
                      title="确定要删除这个地址吗？"
                      onConfirm={() => handleDelete(address.id)}
                      okText="确定"
                      okButtonProps={{
                        style: {
                          height: '22px'
                        }
                      }}
                      cancelText="取消"
                    >
                      <Button 
                        type="text" 
                        size="small"
                        icon={<DeleteOutlined />}
                        danger
                      />
                    </Popconfirm>
                  </div>
                </div>
                
                <div className="address-detail">
                  <EnvironmentOutlined style={{ marginRight: '8px', color: '#666' }} />
                  <span>
                    {address.province} {address.city} {address.district} {address.detail}
                  </span>
                </div>
              </div>
              
              {!address.isDefault && (
                <div className="address-footer">
                  <Button 
                    type="link" 
                    size="small"
                    onClick={() => handleSetDefault(address.id)}
                  >
                    设为默认
                  </Button>
                </div>
              )}
            </div>
          ))}
        </div>
      )}

      {/* 添加地址按钮 */}
      {addresses.length > 0 && (
        <div className="add-address-btn-container">
          <Button 
            type="primary"
            block
            size="large"
            icon={<PlusOutlined />}
            onClick={handleAdd}
          >
            新增收货地址
          </Button>
        </div>
      )}

      {/* 地址编辑模态框 */}
      <Modal
        title={editingAddress ? '编辑地址' : '新增地址'}
        open={modalVisible}
        onOk={handleSubmit}
        onCancel={() => setModalVisible(false)}
        destroyOnClose
        okText="保存"
        okButtonProps={{
          style: {
            height: '30px'
          }
        }}
        cancelText="取消"
        className="address-modal"
        width={300}
      >
        <Form
          form={form}
          layout="vertical"
        >
          <Form.Item
            name="name"
            label="收货人"
            rules={[
              { required: true, message: '请输入收货人姓名' },
              { min: 2, message: '姓名至少2个字符' }
            ]}
          >
            <Input placeholder="请输入收货人姓名" />
          </Form.Item>
          
          <Form.Item
            name="phone"
            label="手机号"
            rules={[
              { required: true, message: '请输入手机号' },
              { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号' }
            ]}
          >
            <Input placeholder="请输入11位手机号码" />
          </Form.Item>
          
          <Form.Item
            name="province"
            label="省份"
            rules={[{ required: true, message: '请输入省份' }]}
          >
            <Input placeholder="请输入省份" />
          </Form.Item>
          
          <Form.Item
            name="city"
            label="城市"
            rules={[{ required: true, message: '请输入城市' }]}
          >
            <Input placeholder="请输入城市" />
          </Form.Item>
          
          <Form.Item
            name="district"
            label="区县"
            rules={[{ required: true, message: '请输入区县' }]}
          >
            <Input placeholder="请输入区县" />
          </Form.Item>
          
          <Form.Item
            name="detail"
            label="详细地址"
            rules={[
              { required: true, message: '请输入详细地址' },
              { min: 1, message: '详细地址不能为空' }
            ]}
          >
            <Input.TextArea 
              placeholder="请输入详细地址，如街道、门牌号等" 
              rows={3} 
            />
          </Form.Item>
          
          {editingAddress && (
            <Form.Item
              name="isDefault"
              valuePropName="checked"
            >
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                <span>设为默认地址</span>
                <Switch />
              </div>
            </Form.Item>
          )}
        </Form>
      </Modal>
    </div>
  );
};

export default AddressManagement; 